// pages/home/home.js
//获取应用实例
var app = getApp();
//引用
var fileData = require('../../utils/data.js')
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    imageUrl: app.globalData.imageUrl,
    userId: '',
    userInfo: '',
    isSign: false,
    banner_url: '',
    advert1: '',
    advert2: '',
    interval: 3000,
    duration: 1000,
    vertical: false,
    indicatordots: true,
    autoplay: true,
    indicatored:'#F08631',
    indicator: '#fff',
    current: '1',
    navTopItems: fileData.getIndexNavData(),
    curNavId: 1,
    curIndex: 0,
    colors: ["red", "orange", "yellow", "green", "purple"],
    focus: '',
    showSignSucess: false,
    advert_url: '',
    actiItem: [],
    bottabData: app.globalData.bottabData,
    imgUrl: app.globalData.imageUrl,
    showRelease:false,
    fbList: app.globalData.fbList,
    isShop:'',
    currentPage: 1,
    hasData: true,
    searchName:'',
    isRead:false
  },
  releaseTap:function(e){
    var item = e.currentTarget.dataset.item;
    if (item.type == 1 || item.type == 4){
      if (this.data.userInfo.brandCar) {
        wx.navigateTo({
          url: item.url
        })
      }else{
        wx.showModal({
          title: '提示',
          content: '你还没有完善车辆信息，请先去完善',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: "/pages/perfectInfo/perfectInfo"
              })
            } else {//取消
            }
          }
        })
      }
    }else{
      if (item.url){
        wx.navigateTo({
          url: item.url
        })
      }
      else{
        if(this.data.isShop == 0){
          wx.navigateTo({
            url: '/pages/seller/seller'
          })
        }
        else if (this.data.isShop == 1) {
          let isOut = wx.getStorageSync("isOut"); 
          if (isOut == 1) {
            wx.showModal({
              title: '提示',
              content: '您的店铺已到期，请续费',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/shopIndex/shopIndex?whole=1'
                  })
                }
              }
            })
          }
          else {
            wx.navigateTo({
              url: '/pages/sjwppublish/sjwppublish'
            })
          }
        }
        else if (this.data.isShop == 2) {
          wx.showToast({
            title: '店铺正在审核中，请稍后发布商品',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  },
  getIsShop: function () {
    var id = JSON.parse(wx.getStorageSync('userInfo')).id;
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopInfo/getOne',
      data: {
        userId: id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (!res.data.success) {
          wx.setStorageSync('isShop', '0');
          wx.removeStorageSync('ShopId');
        }
        else {
          wx.setStorageSync('isOut', res.data.data.dateFlag);
          if (res.data.data.data.status == 1){
            wx.setStorageSync('isShop', '2');
          }
          else{
            wx.setStorageSync('isShop', '1');
            wx.setStorageSync('ShopId', res.data.data.data.id);
          }
        }
        _this.setData({
          isShop: wx.getStorageSync("isShop")
        })
      }
    })
  },
  getIsRead:function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGySystemMessage/noneRead',
      data: {
        toUserId:this.data.userInfo.id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            isRead: res.data.data
          })
        }
      }
    })
  },
  getBannerData: function (block, position, type, key) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyImg/getImgsByParams',
      data: {
        block: block,
        position: position,
        type: type
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            [key]: res.data.data
          })
        }
      }
    })
  },
  enterDesk: function(){
    wx.navigateTo({
      url: '/pages/infoDesk/infoDesk?index=0',
    })
  },
  onSlideChangeEnd: function (e) {
    var that = this;
    that.setData({
      current: e.detail.current + 1
    })
  },  
  switchBotab: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      if (e.currentTarget.dataset.url){
        if (e.currentTarget.dataset.index!=0){
          wx.redirectTo({
            url: e.currentTarget.dataset.url
          })
        }
      }else{
        this.setData({ showRelease:true})
      }
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  hideRelease: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      this.setData({ showRelease: false })
    }
    else {
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  bingfocusFunc: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      this.setData({
        focus: 'focus'
      })
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  bingblurFunc: function(e) {
      this.setData({
        focus: ''
      })
  },
  switchTap: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  enterPerson: function (e) {
    wx.navigateTo({
      url: '/pages/personalProfile/personalProfile?id=' + e.currentTarget.dataset.userid
    })
  },
  // 查看活动详情页
  openDetailPage: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      wx.navigateTo({
        url: "../../pages/activeDetail/activeDetail?id=" + e.target.dataset.id
      })
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  // 获取用户活动信息
  getUserActivity: function (flag) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivity/getAllActivityDetailsByPage',
      data: { 
        userId: this.data.userId,
        name: this.data.searchName,
        currentPage: this.data.currentPage,
        pageNumber: '10'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (flag) {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
        } else {
          _this.setData({
            loadMore: false
          });
        }
        if (res.data.data.activities){
          for (var j = 0; j < res.data.data.activities.length; j++) {
            res.data.data.activities[j].releaseTime = util.formatTime(res.data.data.activities[j].releaseTime)
            _this.data.actiItem.push(res.data.data.activities[j])
          }
          _this.setData({
            actiItem: _this.data.actiItem
          })
        }
        if (res.data.data.page.totalNumber == _this.data.actiItem.length){
          _this.setData({
            hasData: false
          })
        }
      }
        
    })
  },
  search:function(){
    if (wx.getStorageSync('userInfo') != ''){
      wx.navigateTo({
        url: '/pages/seach/seach',
      })
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  // 关注/取消关注
  onunFollowFunc: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      var id = e.currentTarget.dataset.id;
      var index = e.currentTarget.dataset.index;
      var status = e.currentTarget.dataset.status;
      var _this = this;
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/deleteAttentionRecordByParams',
        data: { userId: _this.data.userId, sourceId: id,block: 2},
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            _this.data.actiItem[index][status] = false;
            _this.setData({
              actiItem: _this.data.actiItem
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  onFollowFunc: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      let id = e.currentTarget.dataset.id;
      var index = e.currentTarget.dataset.index;
      var status = e.currentTarget.dataset.status;
      let _this = this;
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/save',
        data: { userId: _this.data.userId, sourceId: id, block: 2 },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            wx.showToast({
              title: '关注成功',
              icon: 'success',
              duration: 2000
            })
            _this.data.actiItem[index][status] = true;
            _this.setData({
              actiItem: _this.data.actiItem
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
    else{
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  // 报名/取消报名
  onunSignFunc: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      let id = e.currentTarget.dataset.id;
      var index = e.currentTarget.dataset.index;
      var status = e.currentTarget.dataset.status;
      let _this = this;
    }
    else{
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  onSignFunc: function (e) {
    if (wx.getStorageSync('userInfo') != '') {
      let item = e.currentTarget.dataset.item;
      var index = e.currentTarget.dataset.index;
      var status = e.currentTarget.dataset.status;
      if(item.fee > 0){
        this.payMoney(item)
      }
      else{
        this.enroll(item.id);
      }
    }
    else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  payMoney: function (item) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivity/payActivityFee',
      data: {
        orderId: item.id,
        openId: app.globalData.openId,
        userId: this.data.userInfo.id,
        money: item.fee,
        body: '活动报名费用'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data,item.id);
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  requestPayment: function (obj,id) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        that.enroll(id)
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
      }
    })
  },
  enroll: function(id){
    let _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivityJoin/joinActivity',
      data: { userId: _this.data.userId, activityId: id },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          wx.showToast({
            title: '报名成功',
            icon: 'success',
            duration: 2000
          })
          _this.data.actiItem[index][status] = true;
          _this.setData({
            actiItem: _this.data.actiItem
          })
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getStorageSync('userInfo')){
      this.setData({
        userInfo: JSON.parse(wx.getStorageSync('userInfo'))
      })
    }
    fileData.getAdvertData.apply(this, ['0', 'advert_url']);
    this.getBannerData('0', 'top', 0, 'banner_url');
    this.getBannerData('0', 'top', 1, 'advert1');
    this.getBannerData('0', 'middle', 1, 'advert2');
    this.getIsSign();
    
    // this.setData({ weatherApikey: getApp().globalData.weatherApikey });
    // this.loadLocation();
  },
  getIsSign: function (e) {
    // let nowyear = new Date().getFullYear(),
    //   nowmonth = new Date().getMonth(),
    //   nowday = new Date().getDate(),
    //   signyear = new Date(this.data.userInfo.signtime).getFullYear(),
    //   signmonth = new Date(this.data.userInfo.signtime).getMonth(),
    //   signday = new Date(this.data.userInfo.signtime).getDate();
    // if (this.data.userInfo.signtime != '' && nowyear == signyear && nowmonth == signmonth && nowday == signday) {
    //   this.setData({
    //     isSign: true
    //   })
    // }
    // else {
    //   this.setData({
    //     isSign: false
    //   })
    // }
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyUserSign/isSign', //仅为示例，并非真实的接口地址
      data: {
        userId: this.data.userInfo.id
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            isSign: res.data.data
          })
        }
      }
    })
  },
  showSignModel: function (e) {
    this.setData({
      showSignSucess: false
    })
  },
  changeSign: function(){
    if (wx.getStorageSync('userInfo') != '') {
      this.setSign();
    }
    else{
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  setSign: function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyUserSign/sign',
      data: {
        userId: this.data.userInfo.id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            showSignSucess: true,
            isSign: true
          })
        }
      }
    })
  },
  hideModel: function(){
    this.setData({
      showSignSucess: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('userInfo') != '') {
      this.getIsShop()
      this.setData({
        userId: JSON.parse(wx.getStorageSync('userInfo')).id,
        userInfo: JSON.parse(wx.getStorageSync('userInfo')),
        ['bottabData[0].current']: true
      })
    }
    this.setData({
      currentPage: 1,
      actiItem: [],
      hasData: true
    });
    this.getUserActivity(true);
    this.getIsRead();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    this.setData({
      currentPage: 1,
      actiItem: [],
      hasData: true
    })
    this.getUserActivity(true)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.hasData) {
      this.setData({
        currentPage: this.data.currentPage + 1
      })
      this.getUserActivity()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})